package com.poker.service;

import com.poker.entity.Product;
import com.poker.repository.ProductRepository;
import com.poker.util.Misc;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName ProductService
 * @Description TODO
 * @Author duyuanyuan
 * @Date 2019/3/13 11:30
 * @Version 1.0
 **/
@Service
public class ProductService {

    @Resource
    private ProductRepository repository;

    /**
     * @param: [page, size];
     * @return: org.springframework.data.domain.Page<Product>;
     * @Description: 不带条件分页查询;
     */
    public Page<Product> findAllProduct(Integer page, Integer size) {
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "createTime");

        return addProperty(repository.findAll(pageable));
    }

    /**
     * @param: [page, size, workOrder];
     * @return: org.springframework.data.domain.Page<WorkOrder>;
     * @Description: 带条件的分页查询;
     */
    public Page<Product> queryProduct(Integer page, Integer size, Product product) {
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "createTime");

        return repository.findAll((Specification<Product>) (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();

            if (Misc.isNotEmpty(product.getProductName()))
                list.add(criteriaBuilder.equal(root.get("productName").as(String.class), product.getProductName()));


            Predicate[] predicateArray = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(predicateArray));
        }, pageable);
    }

    public Product getById(String id) { return addProperty(repository.getOne(id)); }

    @Transactional
    public void update(Product product) {
        Product oldProduct = repository.getOne(product.getId());
        product.setCreateTime(oldProduct.getCreateTime());

        repository.saveAndFlush(product);
    }

    @Transactional
    public void saveProduct(Product product) {
        product.setCreateTime(new Date());
        repository.save(product);
    }

    @Transactional
    public void deleteProduct(Product product) {
        repository.delete(product);
    }

    private Page<Product> addProperty(Page<Product> pages) {
        for (Product product: pages) { addProperty(product); }

        return pages;
    }

    private Product addProperty(Product product) {
        return product;
    }
}
